<?php
  class Utils
  {
    public static function makeClickableLinks($text)
    {
	          $text = html_entity_decode($text);
	          $text = " ".$text;
	          $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
	                  '<a href="\\1" target=_blank>\\1</a>', $text);
	          $text = eregi_replace('(((f|ht){1}tps://)[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
	                  '<a href="\\1" target=_blank>\\1</a>', $text);
	          $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&//=]+)',
	          '\\1<a href="http://\\2" target=_blank>\\2</a>', $text);
	          $text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',
	          '<a href="mailto:\\1" target=_blank>\\1</a>', $text);
	          return $text;
    }

    public static function make_links_blank($text)
    {
        $text = preg_replace(
        array(
        '/(?(?=<a[^>]*>.+<\/a>)
                 (?:<a[^>]*>.+<\/a>)
                 |
                 ([^="\']?)((?:https?|ftp|bf2|):\/\/[^<> \n\r]+)
             )/iex',
        '/<a([^>]*)target="?[^"\']+"?/i',
        '/<a([^>]+)>/i',
        '/(^|\s)(www\.[^<> \n\r]+)/iex',
        //'/(([_A-Za-z0-9-]+)(\\.[_A-Za-z0-9-]+)*@([A-Za-z0-9-]+)(\\.[A-Za-z0-9-]+)*)/iex'
        ),
        array(
        "stripslashes((strlen('\\2')>0?'\\1<a href=\"\\2\">\\2</a>\\3':'\\0'))",
        '<a\\1 target="_blank"',
        '<a\\1 target="_blank">',
        "stripslashes((strlen('\\2')>0?'\\1<a target=\"_blank\" href=\"http://\\2\">\\2</a>\\3':'\\0'))",
        //"stripslashes((strlen('\\2')>0?'<a href=\"mailto:\\0\">\\0</a>':'\\0'))"
        ),
        $text
        );
		
		$matches = array();
        preg_match_all('/<a[^>]*>(.+)<\/a>/U',$text, $matches);
        
        
        
        $patterns = array();
        if(isset($matches[1]))
        {
        	foreach($matches[1] as $string)
        	{
        		//$patterns[] = '/'.strreplace('/','\/',preg_quote($string)).'/';
        		$patterns[] = '/>'.preg_quote($string, '/').'</';
        	}
        	foreach($matches[1] as $key => $string)
        	{
			    $prefix = '';
			    if(strpos($string,'http://') === 0)
			    {
			      $string = substr($string, 7);
			      $prefix = 'http://';
			    }

			    if($pos = strpos($string,'/'))
			    {
			    	if(strlen($string) > $pos + 4)
			    	{
			    	  $pos = $pos + 4;
			    	  $string = substr($string, 0, $pos).'...';
			    	}
			    }
			    $matches[1][$key] = '>'.$prefix.$string.'<';
        	}
        }
        
        //Utils::_printr($patterns);
        //Utils::_printr($matches[1]);
        
        $text = preg_replace($patterns,$matches[1],$text);
        
        /*
        if(isset($matches[1]))
        {
			    if(strpos($matches[1],'http://') === 0)
			    {
			      $matches[1] = substr($matches[1], 7);
			    }

			    if($pos = strpos($matches[1],'/'))
			    {
			    	if(strlen($matches[1]) > $pos + 4)
			    	{
			    	  $pos = $pos + 4;
			    	  $matches[1] = substr($matches[1], 0, $pos).'...';
			    	}
			    }
          //$text = preg_replace('/<a[^>]*>(.+)<\/a>/U',$matches[1],$text);
          $text = preg_replace('/>(.+)</U','>'.$matches[1].'<',$text);
        }
        */
        return $text;
    }
    
    /**
     * validates an email address
     *
     * @param string $email
     * @return boolean
     */
    public static function validateEmail($email) {
        return eregi("^[_a-z0-9-]+(\.[\+_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", 
                $email);
    }

    public static function transliterateString($input = '', $lang = '')
    {
      $originalChars_ro  =  array('ă','â','î','ş','ș','ţ','ț','Ă','Â','Î','Ş','Ţ');
      $translatedChars_ro = array('a','a','i','s','s','t','t','A','A','I','S','T');

      $originalChars_bg  = array('а','б','в','г','д','е', 'ж','з','и','й','к','л','м','н','о','п','р','с','т','у','ф','х', 'ц', 'ч', 'ш',  'щ','ъ','ь', 'ю', 'я', 'А','Б','В','Г','Д','Е', 'Ж','З','И','Й','К','Л','М','Н','О','П','Р','С','Т','У','Ф','Х', 'Ц', 'Ч', 'Ш',  'Щ','Ъ','Ь', 'Ю', 'Я');
      $translatedChars_bg = array('a','b','v','g','d','e','zh','z','i','y','k','l','m','n','o','p','r','s','t','u','f','h','ts','ch','sh','sht','a','y','yu','ya', 'A','B','V','G','D','E','ZH','Z','I','Y','K','L','M','N','O','P','R','S','T','U','F','H','TS','CH','SH','SHT','A','Y','YU','YA');

      $originalChars_rm  = array('а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я', 'А', 'Б', 'В', 'Г', 'Д', 'Е', 'Ё', 'Ж', 'З', 'И', 'Й', 'К', 'Л', 'М', 'Н', 'О', 'П', 'Р', 'С', 'Т', 'У', 'Ф', 'Х', 'Ц', 'Ч', 'Ш', 'Щ', 'Ъ', 'Ы', 'Ь', 'Э', 'Ю', 'Я');
      $translatedChars_rm = array('a', 'b', 'v', 'g', 'd', 'e', 'io', 'j', 'z', 'i', 'i', 'k', 'l', 'm', 'n', 'o', 'p', 'r', 's', 't', 'u', 'f', 'h', 'ts', 'ch', 'sh', 'sch', 'i', 'i', 'i', 'e', 'iu', 'ia', 'A', 'B', 'V', 'G', 'D', 'E', 'IO', 'J', 'Z', 'I', 'I', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'F', 'H', 'TS', 'CH', 'SH', 'SCH', 'I', 'I', 'I', 'E', 'IU', 'IA');

      $originalChars_sr  = array('đ' ,'ž','ć','č','š','Đ' ,'Ž','Ć','Č','Š');
      $translatedChars_sr  = array('dj','z','c','c','s','DJ','Z','C','C','S');

      $originalChars_other = array("À","à","Á","á","Ã","ã","Ä","ä","Å","å","È","è","É","é","Ê","ê","Ë","ë","Ì","ì","Í","í","Ï","ï","Ñ","ñ","Ò","ò","Ó","ó","Ô","ô","Õ","õ","Ö","ö","Ø","ø","Ő","ő","Ù","ù","Ú","ú","Û","û","Ü","ü","Ű","ű");
      $translatedChars_other = array("A","a","A","a","A","a","A","a","A","a","E","e","E","e","E","e","E","e","I","i","I","i","I","i","N","n","O","o","O","o","O","o","O","o","O","o","O","o","O","o","U","u","U","u","U","u","U","u","U","u");

      if($lang != '')
      {
        $originalChars   = ${"originalChars_".$lang};
        $translatedChars = ${"translatedChars_".$lang};
      }
      else
      {
        $originalChars   = array_merge($originalChars_other, $originalChars_bg, $originalChars_ro, $originalChars_sr);
        $translatedChars = array_merge($translatedChars_other, $translatedChars_bg, $translatedChars_ro, $translatedChars_sr);
      }

      $output = str_replace($originalChars, $translatedChars, $input);

      return $output;
    }
  
  public static function slugify($text)
	{
		// replace all non letters or digits by -
    mb_internal_encoding("UTF-8");
    mb_regex_encoding("UTF-8");
    $text = mb_strtolower($text);
    if(sfContext::getInstance()->getUser()->getCulture() == 'ro_RO')
    {
      $text = Utils::transliterateString($text, 'ro');
    }
    if(sfContext::getInstance()->getUser()->getCulture() == 'bg_BG')
    {
      $text = Utils::transliterateString($text, 'bg');
    }
    if(sfContext::getInstance()->getUser()->getCulture() == 'sr_RS')
    {
      $text = Utils::transliterateString($text, 'sr');
    }
    if(sfContext::getInstance()->getUser()->getCulture() == 'ro_MD')
    {
      $text = Utils::transliterateString($text, 'rm');
    }
    
    $text = mb_ereg_replace('[^a-z0-9]', '-', $text);
		 
    // trim
    $text = trim($text, '-');
   
    $text = mb_ereg_replace('[-]+', '-', $text);
		
    if(empty($text))
    {
      return 'n-a';
    }
     
		return $text;
	}
  
  public static function utf8_urldecode($str) {
    $str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\\1;",urldecode($str));
    return html_entity_decode($str,null,'UTF-8');;
  }

	public static function copyImageFromUrl($url, $saved_filename, $path)
	{
	  if($image = file_get_contents($url))
	  {
	    $original_file_name = (false === $pos = strrpos($url, '/')) ? '' : substr($url, $pos + 1);
	    if($original_file_name)
	    {
		    $filename = $saved_filename;

		    if(file_put_contents($path.$filename, $image))
		    {
		    	/*
          if(in_array(exif_imagetype($path.$filename), array(1,2,3)))
		    	{
		    		return $filename;
		    	}
          */
          return $filename;
		    }
	    }	      
	  }
	  if(isset($filename) && file_exists($path.$filename))
	  {
	    unlink($path.$filename);
	  }
	  return false;
	}

     
    public static function resizePhoto($filename, $new_filename, $new_width, $new_height)
    {
      list($width, $height, $type) = getimagesize($filename);
      switch($type)
      {
        case 1: //gif
          $image = imagecreatefromgif($filename);
          break;
        case 2: //jpg
          $image = imagecreatefromjpeg($filename);
          break;
        case 3: //png
          $image = imagecreatefrompng($filename);
          break;
        default: // try jpg
          $image = imagecreatefromjpeg($filename);
      }

      if($image)
      {
        list($width, $height) = getimagesize($filename);
        
        $original_proportion = $width / $height;
        $result_proportion = $new_width / $new_height;
        
        if($original_proportion > $result_proportion)
        {
          $y = 0;
          $x = floor(($width - ($height * $result_proportion)) / 2);
          $crop_width = floor($height * $result_proportion);
          $crop_height = $height;
        }
        else
        {
          $x = 0;
          $y = floor(($height - ($width / $result_proportion)) / 2);          
          $crop_height = floor($width / $result_proportion);
          $crop_width = $width;
        }
        
        /*
        echo '$width='.$width.'<br />';
        echo '$height='.$height.'<br />';
        echo '$new_width='.$new_width.'<br />';
        echo '$new_height='.$new_height.'<br />';
        echo '$original_proportion='.$original_proportion.'<br />';
        echo '$result_proportion='.$result_proportion.'<br />';
        echo '$x='.$x.'<br />';
        echo '$y='.$y.'<br />';        
        echo '$crop_width='.$crop_width.'<br />';
        echo '$crop_height='.$crop_height.'<br />';        
        die();
        */
              
        $new_image = imagecreatetruecolor($new_width, $new_height);
        if(imagecopyresampled($new_image, $image, 0, 0, $x, $y, $new_width, $new_height, $crop_width, $crop_height))
        {
          imagedestroy($image);

          $result = imagejpeg($new_image,$new_filename,80);
          imagedestroy($new_image);
          return array($new_width, $new_height);
        }
        else
        {
          return false;
        }
      }
      else
      {
        return false;
      }
    }
    
    public static function limitString($string, $lenght, $with_dots = false)
    {
        $string = trim($string);
        if(strlen($string) <= $lenght)
        {
            return $string;
        }
        $words = explode(' ',$string);
        $result = '';
        $final_length = 0;
        foreach($words as $word)
        {
            $final_length += strlen($word) + 1;
            if($final_length <= $lenght +1)
            {
                $result .= ' '.$word;
            }
        }
        if($with_dots && (strlen($result) < strlen($string)))
        {
            $result .= '...';
        }
        return trim($result);
    }
    
    public static function formatDate($date)
    {
    	$i18n = sfContext::getInstance()->getI18N();
      
      $datetime = strtotime($date);
    	$now = time();
    	$dif = $now - $datetime;
    	$minute = floor($dif / 60);
    	$ore = floor($dif / 3600);
    	$zile = floor($dif / 86400);
    	$luni = floor($dif / 2592000);
    	$ani = floor($dif / 31104000);
    	
    	if(!$minute && !$ore && !$zile && !$luni && !$ani)
    	{
    		return $i18n->__('a few moments ago');
    	}
    	if(!$ore && !$zile && !$luni && !$ani)
    	{
    		return format_number_choice('[0]1 minute ago|[1]1 minute ago|(1,+Inf]%1% minutes ago', array('%1%' => $minute), $minute);
    	}
    	if(!$zile && !$luni && !$ani)
    	{
    		return format_number_choice('[0]1 hour ago|[1]1 hour ago|(1,+Inf]%1% hours ago', array('%1%' => $ore), $ore);
    	}
    	if(!$luni && !$ani)
    	{
    		return format_number_choice('[0]1 day ago|[1]1 day ago|(1,+Inf]%1% days ago', array('%1%' => $zile), $zile);
    	}
    	if(!$ani)
    	{
    		return format_number_choice('[0]1 month ago|[1]1 month ago|(1,+Inf]%1% months ago', array('%1%' => $luni), $luni);
    	}
   	return format_number_choice('[0]1 year ago|[1]1 year ago|(1,+Inf]%1% years ago', array('%1%' => $ani), $ani);
    }
      
    public static function deleteDirectory($dir)
    {
        if (!file_exists($dir)) return true;
        if (!is_dir($dir)) return unlink($dir);
    	foreach (scandir($dir) as $item) {
            if ($item == '.' || $item == '..') continue;
            if (!Utils::deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) return false;
        }
        return rmdir($dir);
    }
    
    public static function sendMail($subject, $body_text, $body_html, $to, $from_email = null, $from_name = null, $reply_to = null, $type, $force = false)
    {
        if(!$subject || !$to || !($body_text || $body_html))
        {
        	return true;
        }
        
        if($email_blacklist = EmailBlacklistPeer::retrieveByEmail($to))
        {
        	return true;
        }
        
        $send_email = true;
        $mail_limit_per_domain = 100;
        $mail_limit = 300;
        $domain = substr($to,strpos($to,'@'));
        if(!$force)
        {
            $send_email = false;
        }
        else
        {
            $mails_sent_in_last_hour = EmailMessagePeer::countLastHourSentMessages();
	        if($mails_sent_in_last_hour > $mail_limit)
	        {
	        	$send_email = false;
	        }
        }

        if(!$force)
        {
            $send_email = false;
        }
        
        $email_message = new EmailMessage();
        $email_message->setEmail($to);
        $email_message->setDomain($domain);
        $email_message->setType($type);
        $email_message->setFromEmail($from_email);
        $email_message->setFromName($from_name);
        $email_message->setReplyTo($reply_to);
        $email_message->setSubject($subject);
        $email_message->setBodyText($body_text);
        $email_message->setBodyHtml($body_html);
        
        if($send_email)
        {
	        try
	        {
	            ProjectConfiguration::registerZend();
	            $mail = new Zend_Mail('UTF-8');
	            $mail->setBodyText($body_text);
	            $mail->setBodyHtml($body_html);
	            if(!$from_email)
	            {
	            	$from_email = sfConfig::get('app_admin_mail');
		            if(!$from_name)
		            {
		            	$from_name = sfConfig::get('app_admin_name');
		            }
	            }
	            $mail->setFrom($from_email, $from_name);
	            $mail->addTo($to);
	            if($reply_to)
	            {
	            	$mail->setReplyTo($reply_to);
	            }
	            $mail->setSubject($subject);
	            $mail->send($transport);
	            if(sfContext::getInstance()->getUser()->getCulture() == 'ro_RO')
               {
                 $config = array('auth' => 'login',
                                 'username' => sfConfig::get('app_admin_mail'),
                                 'password' => sfConfig::get('app_admin_mail_pass'),
                                  'port' => 25);
                 $transport = new Zend_Mail_Transport_Smtp(sfConfig::get('app_admin_mail_server'), $config);                 
               }
               else
               {
                 $transport = new Zend_Mail_Transport_Sendmail();
               }
	            $email_message->setSentAt(date("Y-m-d H:i:s"));
	        }
	        catch (Exception $e)
	        {
	          // handle errors there
              if($file = fopen(sfConfig::get('sf_upload_dir').'/error_mail_log.txt','a'))
              {
                  $error_message = date("Y-m-d H:i:s").' ('.$to.') : '.$e->getMessage();
                  fwrite($file,$error_message."\n");
                  fclose($file);
              }
	        }
        }
        
        $email_message->save();
    }
    
    public static function sendMailFromDb($email_message)
    {
        $mail_limit_per_domain = 100;
        $mail_limit = 300;
        $mails_sent_in_last_hour = EmailMessagePeer::countLastHourSentMessages();
        if($mails_sent_in_last_hour > $mail_limit)
        {
        	return;
        }
        
        try
        {
            ProjectConfiguration::registerZend();
            $mail = new Zend_Mail('UTF-8');
            $mail->setBodyText($email_message->getBodyText());
            $mail->setBodyHtml($email_message->getBodyHtml());
            $mail->setFrom($email_message->getFromEmail(), $email_message->getFromName());
            $mail->addTo($email_message->getEmail());
            if($email_message->getReplyTo())
            {
            	$mail->setReplyTo($email_message->getReplyTo());
            }
            $mail->setSubject($email_message->getSubject());
            if(sfContext::getInstance()->getUser()->getCulture() == 'ro_RO')
            {
              $config = array('auth' => 'login',
                             'username' => sfConfig::get('app_admin_mail'),
                             'password' => sfConfig::get('app_admin_mail_pass'),
                              'port' => 25);
              $transport = new Zend_Mail_Transport_Smtp(sfConfig::get('app_admin_mail_server'), $config);                 
            }
            else
            {
              $transport = new Zend_Mail_Transport_Sendmail();
            }
            $mail->send($transport);
        }
        catch (Exception $e)
        {
          // handle errors there
          if($file = fopen(sfConfig::get('sf_upload_dir').'/error_mail_log.txt','a'))
          {
              $error_message = date("Y-m-d H:i:s").' ('.$email_message->getId().":".$email_message->getEmail().') : '.$e->getMessage();
              fwrite($file,$error_message."\n");
              fclose($file);
          }
        }
        
        $email_message->setSentAt(date("Y-m-d H:i:s"));
        $email_message->save();
    }
    
    public static function getConfirmCode($email, $type = 'user')
    {
        if($email)
        {
            $code = rand(100, 10000).'-'.rand(1000,90000).'-'.rand(10,999);
            if($type == 'user') $type = 1;
            if($type == 'signup') $type = 2;
            if(!$email_confirm_code = EmailConfirmCodePeer::retrieveByEmail($email))
            {
                $email_confirm_code = new EmailConfirmCode();
            }
            $email_confirm_code->setEmail($email);
            $email_confirm_code->setCode($code);
            $email_confirm_code->setType($type);
            $email_confirm_code->save();
            return $code;
        }
        else
        {
            return null;
        }
    }
    
    public static function getDeveloperIps()
    {
        return array(
            '127.0.0.1',
            '79.112.33.212', // costi
            '192.168.1.102', // costi-lan
            '188.25.47.134', // oana
            '92.80.118.233', // ana
            '93.113.185.157' // dragos ezareni
        );
    }
    
    public static function escape($elements,$string)
    {
        foreach($elements as $element)
        {
            $string = str_replace($element, "\\".$element, $string);
        }
        
        return $string;
    }
    
    public static function shorten($url)
    {
        $bitly = new bitly('dragosholban', 'R_038fc70ec58fd9545728f26548ad25b0');
        return $bitly->shorten(urlencode($url));
    }
    
    /**
    * generare tabel de vouchere pentru magazin - document salvat pe disc
    * 
    * @param int $offer_id ID-ul ofertei pentru care se genereaza lista de vouchere
    * @return string numele fisierului salvat pe disc in /uploads/docs
    */
    public static function generateVoucherTableDoc($offer_id = null)
    {
        if (!$offer_id) {
            return  null;
        }  
        $oferta = OfferPeer::retrieveByPK($offer_id);
        $transactions = $oferta->getTransactions();
        $vouchers = array();
        foreach($transactions as $transaction)
        {
            $vouchers = array_merge($vouchers, $transaction->getVouchers());
        }  
        
      $config = sfTCPDFPluginConfigHandler::loadConfig();
      sfTCPDFPluginConfigHandler::includeLangFile(sfContext::getInstance()->getUser()->getCulture());
     
      $doc_title    = "Tabel Vouchere";
      $doc_subject  = "";
      $doc_keywords = "";
      $html_title = '<h1>Lista Vouchere</h1>';
     
      //create new PDF document (document units are set by default to millimeters)
      $pdf = new sfTCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true);
     
      // set document information
      $pdf->SetCreator(PDF_CREATOR);
      $pdf->SetAuthor(PDF_AUTHOR);
      $pdf->SetTitle($doc_title);
      $pdf->SetSubject($doc_subject);
      $pdf->SetKeywords($doc_keywords);
      
      
     
      $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
     
      //set margins
      $pdf->SetMargins(20, PDF_MARGIN_TOP, 10);
      //$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
     
      //set auto page breaks
      $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
      $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
      $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
      $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); //set image scale factor
     
      $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
      $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
      
      //scot header/footer
      $pdf->setPrintHeader(true);
      $pdf->setPrintFooter(true);
     
      //initialize document
      $pdf->AliasNbPages();
      $pdf->AddPage();
      
      $htmlcontent = '
<b>Oferta:</b> <i>"'.$oferta->getName().'"</i><br />
<b>Magazin:</b> '.$oferta->getProvider()->getName().' ('.$oferta->getProvider()->getFirma().')<br />
<b>Valoare Voucher:</b> '.number_format($oferta->getOfferPrice(),2).' lei<br />
<b>Valabile pana la:</b> '.date('d-m-Y', strtotime($oferta->getVoucherEndDate())).'<br />';
     
      // set barcode
      //$pdf->SetBarcode(date("Y-m-d H:i:s", time()));
     
     //$pdf->Cell(0, 260, '', 1, 0);
     
      // output some HTML code
      $pdf->writeHTML($html_title , true, 0, false, false, 'C');
      $pdf->writeHTML($htmlcontent, true, 0);
      
      //corp factura
     $latime = 180;
     $current_y_position = $pdf->getY();
      $current_x_position = $pdf->GetX()-10;
     $pdf->writeHTMLCell($latime, 0, $current_x_position+10, $current_y_position, '<table width="100%">
    <tr style="font-size:9">
        <td width="5%" align="center">Nr</td>
        <td width="45%">&nbsp;&nbsp;Nume si prenume</td>
        <td width="25%" align="center">Tip plata</td>
        <td width="25%" align="center">Cod Voucher</td>
    </tr>
<table>', 'TB', 2, 0);
    $i=0;
    foreach ($vouchers as $voucher) {
        $i++;
        $pdf->writeHTMLCell($latime, 0, $current_x_position+10, $pdf->GetY(), '<table width="100%">
    <tr style="font-size:12">
        <td width="5%" align="center">'.$i.'</td>
        <td width="45%">'.$voucher->getTransaction()->getAddress()->getBillingFirstName().' '.$voucher->getTransaction()->getAddress()->getBillingLastName().'</td>
        <td width="25%" align="center">'.$voucher->getTransaction()->getPaymentTypeString().'</td>
        <td width="25%" align="center">'.$voucher->getCode().'</td>
    </tr>
<table>', 0, 2, 0);
    }
    
        
      // output two html columns
      /*$first_column_width = 120;
      $current_y_position = $pdf->getY();
      $current_x_position = $pdf->GetX();
      $pdf->writeHTMLCell($first_column_width, 0, $current_x_position+10, $current_y_position, "<b>SC Zumzi SRL</b><br /><br />_________________________<br />Constantin Teleman", 0, 0, 0);
      $pdf->writeHTMLCell(0, 0, $first_column_width, $current_y_position, "<b>".$provider->getFirma()."</b><br /><br />_________________________<br />".$provider->getReprezentant(), 0, 1, 0);*/
     
      // output some content
      //$pdf->Cell(0,10,"TEST Bold-Italic Cell",1,1,'C');
     
      // output some UTF-8 test content
      //$pdf->AddPage();
      //$pdf->SetFont("FreeSerif", "", 12);
     
      //$utf8text = file_get_contents(K_PATH_CACHE. "utf8test.txt", false); // get utf-8 text form file
      //$pdf->SetFillColor(230, 240, 255, true);
      //$pdf->Write(5,$utf8text, '', 1);
     
      // remove page header/footer
      //$pdf->setPrintHeader(false);
      //$pdf->setPrintFooter(false);
     
      // Two HTML columns test
      //$pdf->AddPage();
      /*$right_column = "<b>right column</b> right column right column right column right column
      right column right column right column right column right column right column
      right column right column right column right column right column right column";
      $left_column = "<b>left column</b> left column left column left column left column left
      column left column left column left column left column left column left column
      left column left column left column left column left column left column left
      column";
      $first_column_width = 80;
      $second_column_width = 80;
      $column_space = 20;
      $current_y_position = $pdf->getY();
      $pdf->writeHTMLCell($first_column_width, 0, 0, 0, $left_column, 1, 0, 0);
      $pdf->Cell(0);
      $pdf->writeHTMLCell($second_column_width, 0, $first_column_width+$column_space, $current_y_position, $right_column, 0, 0, 0);*/
     
      // add page header/footer
      /*$pdf->setPrintHeader(true);
      $pdf->setPrintFooter(true);*/
     
      //$pdf->AddPage();
     
      // Multicell test
      /*$pdf->MultiCell(40, 5, "A test multicell line 1\ntest multicell line 2\ntest multicell line 3", 1, 'J', 0, 0);
      $pdf->MultiCell(40, 5, "B test multicell line 1\ntest multicell line 2\ntest multicell line 3", 1, 'J', 0);
      $pdf->MultiCell(40, 5, "C test multicell line 1\ntest multicell line 2\ntest multicell line 3", 1, 'J', 0, 0);
      $pdf->MultiCell(40, 5, "D test multicell line 1\ntest multicell line 2\ntest multicell line 3", 1, 'J', 0, 2);
      $pdf->MultiCell(40, 5, "F test multicell line 1\ntest multicell line 2\ntest multicell line 3", 1, 'J', 0);*/
     
        $docName = 'Lista_vouchere_'.$oferta->getId().'_'.str_replace(' ','_', trim($oferta->getProvider()->getName())).'.pdf';
      // Close and output PDF document
      $pdf->Output('uploads/docs/'.$docName, 'F');
      return $docName;
      // Stop symfony process
      throw new sfStopException();
    }
    
    /**
    * generare factura fiscala pentru comision plata online - salvare pe disc in /uploads/docs
    * 
    * @param int $offer_id ID-ul ofertei pt care se genereaza FF1
    * @return String numele fisierului generat in /uploads/docs , sau erroare (1 - datele de facturare sunt incomplete; 2 - comisionul Zumzi este 0; 3 - nu sunt plati online pentru aceasta oferta; 4 - nu exista contract pt oferta; )
    */
    public static function generateff1($offer_id)
    {
        if (!$offer_id) {
            return '';
        } 
        $oferta = OfferPeer::retrieveByPK($offer_id);
        $provider = $oferta->getProvider();
        
        //verific daca s-au completat datele provider
        if ($provider->getFirma() == '' || 
            $provider->getAddresaFf() == '' || 
            $provider->getNrregcom() == '' || 
            $provider->getCui() == '' || 
            $provider->getIban() == '' || 
            $provider->getBanca() == ''
        ) {
            return '1';
        }
        //verific daca s-au completat datele provider - over
        
        //verific daca comision + taxa e completat la oferta
        if ($oferta->getComision() == 0) {
            return '2';
        }
        //verific daca comision + taxa e completat la oferta - over
        
        //verific daca sunt plati online
        $c = new Criteria();
        $c->add(TransactionPeer::PAYMENT_TYPE, 1);
        $c->add(TransactionPeer::STATE, 2);
        $c->add(TransactionPeer::OFFER_ID, $oferta->getId());
        $transactionsOnline = $oferta->getTransactions($c);
        if (count($transactionsOnline) == 0) {
            return '3';
        }
        //verific daca sunt plati online - over
        
        //verific daca exista contract
        $contracts = $oferta->getContracts();
        if (count($contracts) == 0) {
            return '4';
        } else {
            $contract = $contracts[0];
        }
        //verific daca exista contract - over
        
        //creez factura in DB daca nu este deja
        $c = new Criteria();
        $c->add(FacturaPeer::PROVIDER_ID, $provider->getId());
        $c->add(FacturaPeer::OFFER_ID, $oferta->getId());
        $c->add(FacturaPeer::TIP, 1);
        $factura = FacturaPeer::doSelectOne($c);
        if (!$factura) {
            $factura = new Factura();
            $factura->setTip(1);
            $factura->setNumar(FacturaPeer::getMaxNumar()+1);
            $factura->setProvider($provider);
            $factura->setOffer($oferta);
            $factura->setReleaseDate(mktime(0, 0, 0, date('m', strtotime($oferta->getEndDate())), date('d', strtotime($oferta->getEndDate()))+1, date('Y', strtotime($oferta->getEndDate()))));
            $factura->setCantitate(count($transactionsOnline));
            $factura->setPretUnitar($oferta->getComision());
            $factura->setValoare($factura->getCantitate() * $oferta->getComision());
            $factura->save();
        }
        
      $config = sfTCPDFPluginConfigHandler::loadConfig();
      sfTCPDFPluginConfigHandler::includeLangFile(sfContext::getInstance()->getUser()->getCulture());
     
      $doc_title    = "Factura Fiscala";
      $doc_subject  = "";
      $doc_keywords = "";
      $html_title = '';
      $htmlcontent = '<table border="0" width="100%">
      <tr>
        <td>
            &nbsp;&nbsp;&nbsp;<img src="/images/pdf/logo_zumzi.jpg" border="0" width="400"/>            
        </td>
        <td style="font-size:9">
            <b>Factura Seria:</b> ZM  <b>Nr:</b> 00'.$factura->getNumar().'<br />
            <b>Data:</b> '.$factura->getReleaseDate('d-m-Y').'
        </td>
      </tr>
      <tr>
        <td rowspan="15" width="5%"></td>
        <td>
            <span style="font-size:13; font-weight: bold;">Furnizor:</span><br />
            <b>SC ZUMZI SRL</b><br />
            <span style="font-size:9;"><b>Reg.Com.:</b> J22/54/2010<br />
            <b>CUI:</b> 26415079  ATR.F:-<br />
            <b>Adresa:</b> Iasi, Str. A. Panu nr.54, bl.H1, et.1, ap.2<br />
            <b>Judetul:</b> Iasi<br />
            <b>Cont:</b> RO35INGB0000999901947362<br />
            <b>Banca:</b> ING Bank IASI<br />
            <b>Capital social:</b> 200,00 RON</span>
        </td>
        <td>
            <span style="font-size:13; font-weight: bold;">Cumparator:</span><br />
            <b>'.$provider->getFirma().'</b><br />
            <span style="font-size:9;"><b>Reg.Com.:</b> '.$provider->getNrregcom().'<br />
            <b>CUI:</b> '.$provider->getCui().'<br />
            <b>Adresa:</b> '.$provider->getAddresaFf().'<br />
            <b>Cont:</b> '.$provider->getIban().'<br />
            <b>Banca:</b> '.$provider->getBanca().'</span>
        </td>
      </tr> 
      <tr>
        <td align="center" style="font-size: 25" colspan="2"><br /><br />FACTURA</td>
      </tr>     
</table>';
     
      //create new PDF document (document units are set by default to millimeters)
      $pdf = new sfTCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true);
     
      // set document information
      $pdf->SetCreator(PDF_CREATOR);
      $pdf->SetAuthor(PDF_AUTHOR);
      $pdf->SetTitle($doc_title);
      $pdf->SetSubject($doc_subject);
      $pdf->SetKeywords($doc_keywords);
      
      
     
      //$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
     
      //set margins
      $pdf->SetMargins(20, 10, 10);
     
      //set auto page breaks
      $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
      $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
      $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
      $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); //set image scale factor
     
      $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
      $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
      
      //scot header/footer
      $pdf->setPrintHeader(false);
      $pdf->setPrintFooter(false);
     
      //initialize document
      $pdf->AliasNbPages();
      $pdf->AddPage();
     
      // set barcode
      //$pdf->SetBarcode(date("Y-m-d H:i:s", time()));
     
     $pdf->Cell(0, 260, '', 1, 0);
     
      // output some HTML code
      $pdf->writeHTML($html_title , true, 0, false, false, 'C');
      $pdf->writeHTML($htmlcontent, true, 0);
      
      //corp factura
     $latime = 180;
     $current_y_position = $pdf->getY();
      $current_x_position = $pdf->GetX()-10;
     $pdf->writeHTMLCell($latime, 0, $current_x_position+10, $current_y_position, '<table width="100%">
    <tr style="font-size:9">
        <td width="5%" align="center">Nr</td>
        <td width="45%">&nbsp;&nbsp;Denumirea produselor sau serviciilor</td>
        <td width="5%" align="center">U.M.</td>
        <td width="15%" align="center">Cantitatea</td>
        <td width="15%" align="center">Pret unitar</td>
        <td width="15%" align="center">Valoarea</td>
    </tr>
<table>', 'TB', 2, 0);
    $pdf->writeHTMLCell($latime, 0, $current_x_position+10, $pdf->GetY(), '<table width="100%">
    <tr style="font-size:12">
        <td width="5%" align="center">1</td>
        <td width="45%">Comision servicii publicitate aferente incasarilor prin prestator conform contract nr '.$contract->getId().'/'.date('d-m-Y',strtotime($contract->getCreatedAt())).'</td>
        <td width="5%" align="center">buc</td>
        <td width="15%" align="center">'.$factura->getCantitate().'</td>
        <td width="15%" align="center">'.(number_format($factura->getPretUnitar(),2,',','.')).'</td>
        <td width="15%" align="center">'.(number_format($factura->getValoare(),2,',','.')).'</td>
    </tr>
<table>', 0, 2, 0);
        
        $pdf->writeHTMLCell($latime, 0, $current_x_position+10, $pdf->GetY()+70, '<table width="100%">
    <tr style="font-size:12">
        <td>Termen de plata: 0 zile de la primirea acestei facturi</td>
    </tr>
<table>', 0, 2, 0);
        $pdf->writeHTMLCell($latime, 0, $current_x_position+10, $pdf->GetY(), '<table width="100%">
    <tr style="font-size:9">
        <td>Neplatitor TVA conf.art.152,al.(1) L.571/2003 Cod Fiscal</td>
    </tr>
<table>', 0, 2, 0);
        $pdf->writeHTMLCell($latime, 0, $current_x_position+10, $pdf->GetY(), '<table width="100%">
    <tr style="font-size:9">
        <td><b>Intocmit:</b> Constantin Teleman, CNP: 1780425221138</td>
    </tr>
<table>', "TB", 2, 0);
        $pdf->writeHTMLCell($latime/4, 30, $current_x_position+10, $pdf->GetY(), '<table width="100%">
    <tr style="font-size:8">
        <td><b>Semnatura si stampila furnizorului</b><br /><img src="/images/pdf/semnatura.jpg" border="0" width="300"/></td>
    </tr>
<table>', 'TRB', 0, 0);
        $pdf->writeHTMLCell($latime/4, 30, $current_x_position+10+$latime/4, $pdf->GetY(), '<table width="100%">
    <tr style="font-size:8">
        <td><b>Date privind expeditia:</b><br /><br />Transmisa electronic la adresa '.$oferta->getProviderEmail().'</td>
    </tr>
<table>', 'TRB', 0, 0);
        $pdf->writeHTMLCell($latime/4, 30, $current_x_position+10+2*$latime/4, $pdf->GetY(), '<table width="100%">
    <tr style="font-size:8">
        <td><b>Semnatura de primire</b></td>
    </tr>
<table>', 'TRB', 0, 0);
        $pdf->writeHTMLCell($latime/4, 30, $current_x_position+10+3*$latime/4, $pdf->GetY(), '<table width="100%">
    <tr style="font-size:8">
        <td><b>Total de plata:</b><br /><br /></td>
    </tr>
    <tr style="font-size:12">
        <td align="center"><b>'.number_format($factura->getValoare(), 2, ',', '.').'</b></td>
    </tr>
<table>', 'TB', 2, 0);
        $pdf->writeHTMLCell($latime, 0, $current_x_position+10, $pdf->GetY(), '<table width="100%">
    <tr style="font-size:8">
        <td>* Factura este emisa in mod electronic si nu necesita stampila si semnatura in conformitate cu Codul Fiscal si legislatia in vigoare</td>
    </tr>
<table>', 0, 2, 0);
     
      // output two html columns
      /*$first_column_width = 120;
      $current_y_position = $pdf->getY();
      $current_x_position = $pdf->GetX();
      $pdf->writeHTMLCell($first_column_width, 0, $current_x_position+10, $current_y_position, "<b>SC Zumzi SRL</b><br /><br />_________________________<br />Constantin Teleman", 0, 0, 0);
      $pdf->writeHTMLCell(0, 0, $first_column_width, $current_y_position, "<b>".$provider->getFirma()."</b><br /><br />_________________________<br />".$provider->getReprezentant(), 0, 1, 0);*/
     
      // output some content
      //$pdf->Cell(0,10,"TEST Bold-Italic Cell",1,1,'C');
     
      // output some UTF-8 test content
      //$pdf->AddPage();
      //$pdf->SetFont("FreeSerif", "", 12);
     
      //$utf8text = file_get_contents(K_PATH_CACHE. "utf8test.txt", false); // get utf-8 text form file
      //$pdf->SetFillColor(230, 240, 255, true);
      //$pdf->Write(5,$utf8text, '', 1);
     
      // remove page header/footer
      //$pdf->setPrintHeader(false);
      //$pdf->setPrintFooter(false);
     
      // Two HTML columns test
      //$pdf->AddPage();
      /*$right_column = "<b>right column</b> right column right column right column right column
      right column right column right column right column right column right column
      right column right column right column right column right column right column";
      $left_column = "<b>left column</b> left column left column left column left column left
      column left column left column left column left column left column left column
      left column left column left column left column left column left column left
      column";
      $first_column_width = 80;
      $second_column_width = 80;
      $column_space = 20;
      $current_y_position = $pdf->getY();
      $pdf->writeHTMLCell($first_column_width, 0, 0, 0, $left_column, 1, 0, 0);
      $pdf->Cell(0);
      $pdf->writeHTMLCell($second_column_width, 0, $first_column_width+$column_space, $current_y_position, $right_column, 0, 0, 0);*/
     
      // add page header/footer
      /*$pdf->setPrintHeader(true);
      $pdf->setPrintFooter(true);*/
     
      //$pdf->AddPage();
     
      // Multicell test
      /*$pdf->MultiCell(40, 5, "A test multicell line 1\ntest multicell line 2\ntest multicell line 3", 1, 'J', 0, 0);
      $pdf->MultiCell(40, 5, "B test multicell line 1\ntest multicell line 2\ntest multicell line 3", 1, 'J', 0);
      $pdf->MultiCell(40, 5, "C test multicell line 1\ntest multicell line 2\ntest multicell line 3", 1, 'J', 0, 0);
      $pdf->MultiCell(40, 5, "D test multicell line 1\ntest multicell line 2\ntest multicell line 3", 1, 'J', 0, 2);
      $pdf->MultiCell(40, 5, "F test multicell line 1\ntest multicell line 2\ntest multicell line 3", 1, 'J', 0);*/
     
      $docName = 'ZM00'.$factura->getNumar().'_'.$factura->getReleaseDate('dmY').'.pdf';
      // Close and output PDF document
      $pdf->Output('uploads/docs/'.$docName, 'F');
      
      return $docName;
     
      // Stop symfony process
      throw new sfStopException();
    }
    
    public static function generateVouchers($offer_id)
    {
        if($offer = OfferPeer::retrieveByPK($offer_id))
        {
            if($offer->isValidated())
            {
                $transactions = $offer->getTransactions();
                foreach($transactions as $transaction)
                {
                    if(in_array($transaction->getState(), array(1,2)) && (($transaction->getPaymentType() == 2 && $transaction->getIsConfirmed()) || ($transaction->getPaymentType() == 1 && $transaction->getState() == 2) || ($transaction->getPaymentType() == 3 && $transaction->getState() == 2)))
                    {
                        if(!count($transaction->getVouchers()))
                        {
                          
                            if(0 && $offer->getId() == '89') {//coduri custom pentru oferta cu ceasuri
                              
                              for($i = 0; $i < $transaction->getPieces(); $i++)
                              {
                                  //iau un cod nefolosit
                                  $connection = Propel::getConnection();
                                  $query = "select code from codes where is_used = 0 limit 1";
                                  $statement = $connection->prepare($query);
                                  $resultset = $statement->execute();
                                  $resultset = $statement->fetch(PDO::FETCH_ASSOC);
                                  $code = $resultset['code'];
                                  
                                  //generez voucherul cu acel cod
                                  $voucher = new Voucher();
                                  $voucher->setTransactionId($transaction->getId());
                                  $voucher->setCode($code);
                                  $voucher->save();
                                  $vouchers[] = $voucher;
                                  
                                  //updatez codul in DB - is_used = 1
                                  $connection = Propel::getConnection();
                                  $query = "update codes set is_used = 1 where code = '".$code."'";
                                  $statement = $connection->prepare($query);
                                  $resultset = $statement->execute();
                              }
                            } else {//generare coduri normale
                              $codes = array();
                              $vouchers = array();
                              for($i = 0; $i < $transaction->getPieces(); $i++)
                              {
                                  $code = rand(100000,999999);
                                  while(in_array($code, $codes))
                                  {
                                      $code = rand(100000,999999);
                                  }
                                  $codes[] = $code;
                                  $voucher = new Voucher();
                                  $voucher->setTransactionId($transaction->getId());
                                  $voucher->setCode(($transaction->getOffer()->getId() * 5 + 31).'-'.($transaction->getId() * 3).'-'.$code);
                                  $voucher->save();
                                  $vouchers[] = $voucher;
                              }
                            }
                            //send emails
                            if(count($vouchers))
                            {
                                $emails = array();
                                $sent_emails = array();
                                if($user = $transaction->getUser())
                                {
                                    $emails[] = $user->getEmail();
                                }
                                if($address = $transaction->getAddress())
                                {
                                    if($address->getBillingEmail())
                                    {
                                        $emails[] = $address->getBillingEmail();
                                    }
                                    if($address->getShippmentEmail())
                                    {
                                        $emails[] = $address->getShippmentEmail();
                                    }
                                }
                                $emails = array_unique($emails);
                                foreach($emails as $email)
                                {
                                    if($email)
                                    {
                                        $mailContext = array('offer' => $offer, 'transaction' => $transaction, 'vouchers' => $vouchers);
                                        $subject = sfContext::getInstance()->getI18N()->__('Zumzi - Validated Offer');
                                        sfContext::getInstance()->getConfiguration()->loadHelpers('Partial');
                                        $bodyText = get_partial('mail/sendOfferValidatedText', $mailContext);
                                        $bodyHtml = get_partial('mail/sendOfferValidatedHtml', $mailContext);
                                        Utils::sendMail($subject, $bodyText, $bodyHtml, $email, sfConfig::get('app_offer_mail'), sfConfig::get('app_offer_name'), null, 'oz_validated', false);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    public static function NeoDecrypt($app_key, $neo_coded)
    {
        $enc = base64_decode(strtr($neo_coded, '-._', '+/='));  
        return mcrypt_decrypt( MCRYPT_TRIPLEDES, $app_key, substr($enc, 8), MCRYPT_MODE_CBC, substr($enc, 0, 8) );
    }
    
    public static function sendCardTransactionError($transaction, $cod_eroare, $mesaj_eroare)
    {
        $user = $transaction->getUser();
        $offer = $transaction->getOffer();
        // send mail to user
        $emails = array();
        $sent_emails = array();
        $emails[] = $user->getEmail();

        if($address = $transaction->getAddress())
        {
            if($address->getBillingEmail())
            {
                $emails[] = $address->getBillingEmail();
            }
            if($address->getShippmentEmail())
            {
                $emails[] = $address->getShippmentEmail();
            }
        }
        
        $emails = array_unique($emails);
        foreach($emails as $email)
        {
            if($email && !in_array($email, $sent_emails))
            {
                $mailContext = array('offer' => $offer, 'transaction' => $transaction, 'cod_eroare' => $cod_eroare, 'mesaj_eroare' => $mesaj_eroare);
                $subject = 'Zumzi - Eroare tranzactie';
                sfContext::getInstance()->getConfiguration()->loadHelpers('Partial');
                $bodyText = get_partial('mail/sendCardTransactionErrorText', $mailContext);
                $bodyHtml = get_partial('mail/sendCardTransactionErrorHtml', $mailContext);
                
                Utils::sendMail($subject, $bodyText, $bodyHtml, $email, sfConfig::get('app_offer_mail'), sfConfig::get('app_offer_name'), null, 'order_confirmation', false);
                $sent_emails[] = $email;
            }
        }
    }
    
    public static function curl_post($url, array $post = NULL, array $options = array())
    {
        $defaults = array(
            CURLOPT_POST => 1,
            CURLOPT_HEADER => 0,
            CURLOPT_URL => $url,
            CURLOPT_FRESH_CONNECT => 1,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_FORBID_REUSE => 1,
            CURLOPT_TIMEOUT => 10,
            CURLOPT_POSTFIELDS => http_build_query($post)
        );

        $ch = curl_init();
        curl_setopt_array($ch, ($options + $defaults));
        if( ! $result = curl_exec($ch))
        {
            trigger_error(curl_error($ch));
        }
        curl_close($ch);
        return $result;
    } 
    
    public static function phplistSubscribe($email, $city_id)
    {
      if(sfContext::getInstance()->getUser()->getCulture() == 'ro_RO')
      {  
        Utils::curl_post("http://phplist.zumzi.ro/?p=subscribe", array("email" => $email, "emailconfirm" => $email, "list[1]" => "signup", "listaname[1]" => "test", "htmlemail" => "1", "VerificationCodeX" => "", "subscribe" => "Subscribe", "makeconfirmed" => "1", "passwordreq" => "", "password" => "", "attribute1" => array($city_id), "fromapi" => 1));
      }
    }
    
    public static function createPhplistMessage($subject, $fromEmail, $fromName, $bodyText, $bodyHtml, $city_id)
    {
        $userselection = "select table1.userid from phplist_user_user_attribute as table1  where table1.attributeid = 1 and (find_in_set('".$city_id."',table1.value) > 0)";
        
        //oferta pentru Zumzi.ro
        $link = mysql_connect('my5592.d9364.myhost.ro', '9364zumziuser', 'zumziroot');
        if(!$link)
        {
            die('Could not connect: ' . mysql_error());
        }
        mysql_select_db('zumzi_ro_phplist');
        
        $sql = "INSERT INTO phplist_message (
                subject,
                fromfield,
                tofield,
                replyto,
                message,
                textmessage,
                footer,
                entered,
                modified,
                embargo,
                repeatinterval,
                repeatuntil,
                status,
                userselection,
                sent,
                htmlformatted,
                sendformat,
                template,
                processed,
                astext,
                ashtml,
                astextandhtml,
                aspdf,
                astextandpdf,
                viewed,
                bouncecount,
                sendstart,
                rsstemplate,
                owner
                )
                VALUES (
                '".mysql_real_escape_string($subject)."',
                '".mysql_real_escape_string($fromName." ".$fromEmail)."',
                '',
                '',
                '".mysql_real_escape_string($bodyHtml)."',
                '".mysql_real_escape_string($bodyText)."',
                '',
                '".date("Y-m-d H:i:s")."',
                '".date("Y-m-d H:i:s")."',
                '".date("Y-m-d H:i:s")."',
                '0',
                '".date("Y-m-d H:i:s")."',
                'inprocess',
                '".mysql_real_escape_string($userselection)."',
                NULL,
                '1',
                'HTML',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                NULL,
                '',
                '1'
                )
        ";
        $result = mysql_query($sql);

        // Check result
        // This shows the actual query sent to MySQL, and the error. Useful for debugging.
        if (!$result) {
            $message  = 'Invalid query: ' . mysql_error() . "\n";
            $message .= 'Whole query: ' . $sql;
            die($message);
        }
        
        $sql = "INSERT INTO phplist_listmessage (
                messageid,
                listid,
                entered,
                modified
                )
                VALUES (
                '".mysql_insert_id()."',
                '1',
                '".date("Y-m-d H:i:s")."',
                '".date("Y-m-d H:i:s")."'
                )
        ";
        $result = mysql_query($sql);

        // Check result
        // This shows the actual query sent to MySQL, and the error. Useful for debugging.
        if (!$result) {
            $message  = 'Invalid query: ' . mysql_error() . "\n";
            $message .= 'Whole query: ' . $sql;
            die($message);
        }
        
        mysql_close($link);
         //oferta pentru Zumzi.ro - over
         
        /*
        //oferta pentru Zumzi.com       
        $link = mysql_connect('my6869.d14062.myhost.ro', '14062zumzi', 'zumziroot');
        if(!$link)
        {
            die('Could not connect: ' . mysql_error());
        }
        mysql_select_db('zumzi_com_phplist');
        
        $sql = "INSERT INTO phplist_message (
                subject,
                fromfield,
                tofield,
                replyto,
                message,
                textmessage,
                footer,
                entered,
                modified,
                embargo,
                repeatinterval,
                repeatuntil,
                status,
                userselection,
                sent,
                htmlformatted,
                sendformat,
                template,
                processed,
                astext,
                ashtml,
                astextandhtml,
                aspdf,
                astextandpdf,
                viewed,
                bouncecount,
                sendstart,
                rsstemplate,
                owner
                )
                VALUES (
                '".mysql_real_escape_string($subject)."',
                'Zumzi admin@zumzi.com',
                '',
                '',
                '".mysql_real_escape_string($bodyHtml)."',
                '".mysql_real_escape_string($bodyText)."',
                '',
                '".date("Y-m-d H:i:s")."',
                '".date("Y-m-d H:i:s")."',
                '".date("Y-m-d H:i:s")."',
                '0',
                '".date("Y-m-d H:i:s")."',
                'inprocess',
                '".mysql_real_escape_string($userselection)."',
                NULL,
                '1',
                'HTML',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                '0',
                NULL,
                '',
                '1'
                )
        ";
        $result = mysql_query($sql);

        // Check result
        // This shows the actual query sent to MySQL, and the error. Useful for debugging.
        if (!$result) {
            $message  = 'Invalid query: ' . mysql_error() . "\n";
            $message .= 'Whole query: ' . $sql;
            die($message);
        }
        
        $sql = "INSERT INTO phplist_listmessage (
                messageid,
                listid,
                entered,
                modified
                )
                VALUES (
                '".mysql_insert_id()."',
                '3',
                '".date("Y-m-d H:i:s")."',
                '".date("Y-m-d H:i:s")."'
                ), 
                (
                '".mysql_insert_id()."',
                '4',
                '".date("Y-m-d H:i:s")."',
                '".date("Y-m-d H:i:s")."'
                )
        ";
        $result = mysql_query($sql);

        // Check result
        // This shows the actual query sent to MySQL, and the error. Useful for debugging.
        if (!$result) {
            $message  = 'Invalid query: ' . mysql_error() . "\n";
            $message .= 'Whole query: ' . $sql;
            die($message);
        }
        
        mysql_close($link);  
        //oferta pentru Zumzi.com - over
        */        
    }
    
    /**
    * executa sctiunea de unsubscribe pentru o adresa de email la newsletterul Neogen
    * 
    * @param string $email Adresa pentru care se face unscubscribe
    * @param Array $options array cu alte optiuni pentru curl
    */
    public static function unsubscribeNeogenNl($email, array $options = array())
    {
      $code = md5('YMjfHDnGgBNR82rN374p'.$email);
      $url = 'http://www.neogen.ro/unsubscribe/email/'.$email.'/code/'.$code;
      
      $defaults = array(
            CURLOPT_POST => 0,
            CURLOPT_HEADER => 0,
            CURLOPT_URL => $url,
            CURLOPT_FRESH_CONNECT => 1,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_FORBID_REUSE => 1,
            CURLOPT_TIMEOUT => 10,
        );

        $ch = curl_init();
        curl_setopt_array($ch, ($options + $defaults));
        if( ! $result = curl_exec($ch))
        {
          trigger_error(curl_error($ch));
        }
        curl_close($ch);
        
        if (strpos($result, 'Cererea de dezabonare a fost procesata cu succes.') !== false) {
          return true;
        } else {
          //trigger_error('Eroare la unsubscribe Neogen NL pentru adresa: '.$email);
          return false;
        }
    }

    /**
    * used by Epay.bg
    */    
    public static function hmac($algo,$data,$passwd)
    {
            /* md5 and sha1 only */
            $algo=strtolower($algo);
            $p=array('md5'=>'H32','sha1'=>'H40');
            if(strlen($passwd)>64) $passwd=pack($p[$algo],$algo($passwd));
            if(strlen($passwd)<64) $passwd=str_pad($passwd,64,chr(0));

            $ipad=substr($passwd,0,64) ^ str_repeat(chr(0x36),64);
            $opad=substr($passwd,0,64) ^ str_repeat(chr(0x5C),64);

            return($algo($opad.pack($p[$algo],$algo($ipad.$data))));
    }
    
    public static function domNodeContent($n, $outer=false)
    {
        $d = new DOMDocument('1.0');
        $b = $d->importNode($n->cloneNode(true),true);
        $d->appendChild($b); $h = $d->saveHTML();
        // remove outter tags
        if (!$outer) $h = substr($h,strpos($h,'>')+1,-(strlen($n->nodeName)+4));
        return $h;
    }
    
    public static function domNodeTextContent($n)
    {
      $text = '';
      if($n->hasChildNodes())
      {
        $childNodes = $n->childNodes;
        for($i = 0; $i < $childNodes->length; $i++)
        {
          $childNode = $childNodes->item($i);
          $text .= Utils::domNodeTextContent($childNode);
        }
      }
      else
      {
        return $n->nodeValue.' ';
      }
      
      return $text;
    }
    
    public static function subString($string, $start, $end = null)
    {
      $part1 = null;
      
      $pos = strpos($string, $start);
      if(!$start)
      {
        $pos = 0;
      }
      if($pos !== false)
      {
        $part1 = substr($string, $pos + strlen($start));
        if($end)
        {
          $pos = strpos($part1, $end);
          if($pos !== false)
          {
            return trim(substr($part1, 0, $pos));
          }
        }
      }
      
      return $part1;
    }
    
    public static function curl_exec_follow(/*resource*/ $ch, /*int*/ &$maxredirect = null)
    {
      $mr = $maxredirect === null ? 5 : intval($maxredirect);
      if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off'))
      {
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $mr > 0);
        curl_setopt($ch, CURLOPT_MAXREDIRS, $mr);
      }
      else
      {
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
        if ($mr > 0)
        {
            $newurl = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);

            $rch = curl_copy_handle($ch);
            curl_setopt($rch, CURLOPT_HEADER, true);
            curl_setopt($rch, CURLOPT_NOBODY, true);
            curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
            curl_setopt($rch, CURLOPT_RETURNTRANSFER, true);
            do {
                curl_setopt($rch, CURLOPT_URL, $newurl);
                $header = curl_exec($rch);
                if (curl_errno($rch)) {
                    $code = 0;
                } else {
                    $code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
                    if ($code == 301 || $code == 302) {
                        preg_match('/Location:(.*?)\n/', $header, $matches);
                        $newurl = trim(array_pop($matches));
                    } else {
                        $code = 0;
                    }
                }
            } while ($code && --$mr);
            curl_close($rch);
            if (!$mr) {
                if ($maxredirect === null) {
                    trigger_error('Too many redirects. When following redirects, libcurl hit the maximum amount.', E_USER_WARNING);
                } else {
                    $maxredirect = 0;
                }
                return false;
            }
            curl_setopt($ch, CURLOPT_URL, $newurl);
        }
      }
      return curl_exec($ch);
    }
    
    public static function cleanText($text)
    {
      $text = iconv('UTF-8', 'ASCII//TRANSLIT', $text);
      //$text = preg_replace('/[^(0-9a-zA-Z.,-_ \/!?@#%&*()+"=\')]*/','', $text);

      return $text;
    }
    
  /**
   * from google documentation @see http://code.google.com/apis/analytics/docs/gaJS/gaJSApiEventTracking.html
   * You can omit either or both opt_label or opt_value. If you supply opt_value without opt_label, you need to pass in undefined for the optional label.
   * @param string $category, The general event category (e.g. "Videos").
   * @param string $action, The action for the event (e.g. "Play").
   * @param string $opt_label, An optional descriptor for the event.
   * @param int $opt_value, An optional value associated with the event. You can see your event values in the Overview, Categories, and Actions reports, where they are listed by event or aggregated across events, depending upon your report view.
   * @return string, js code to attach in onclick event
   */
  public static function gaTrackEvent($category, $action, $opt_label='', $opt_value=0)
  {
      $return = "try{_gaq.push(['_trackEvent', '".$category."', '".$action."'";
      if (empty($opt_label) && !empty($opt_value))
          $return .= ",'undefined', ".(int)$opt_value;
      if (!empty($opt_label) && !empty($opt_value))
          $return .= ",'".$opt_label."', ".(int)$opt_value;
      $return .= "]);}catch(e){;};";
      return $return;
  }
  }